<template>
    <div class="m-25 mt-65">
        <div class="normal-box-mod">
            <div class="normal-box-hd clearfix">
                <div class="normal-box-title">
                    <div class="decorate-square"></div>
                    <h2>角色组管理</h2>
                </div>
            </div>
            <div class="normal-box-bd">
                <div class="mb-20">
                    <Button type="primary"
                            @click="show_create_role_group_modal">
                        <Icon type="plus"></Icon> 添加顶级角色组
                    </Button>
                </div>
                <Row :gutter="16">
                    <Col span="8">
                    <Card>
                        <div slot="title">角色组</div>
                        <Tree :data="role_group_tree_data"
                              @on-select-change="get_node_info"></Tree>
                    </Card>
                    </Col>
                    <Col span="16">
                    <Card v-if="current_select_node_data.code">
                        <div slot="title">角色组详情</div>
                        <div class="mb-20">
                            <ButtonGroup>
                                <Button @click="show_create_sub_role_group_modal">
                                    <Icon type="plus"></Icon> 添加子角色组
                                </Button>
                                <Button @click="show_access_allot_modal">
                                    <Icon type="navicon"></Icon> 菜单权限分配
                                </Button>
                                <!-- <Button @click="show_element_permission_modal">
                                    <Icon type="grid"></Icon> 页面元素权限分配</Button> -->
                                <!-- <Button @click="show_connect_user_modal">
                                    <Icon type="link"></Icon> 关联用户</Button> -->
                                <Button @click="show_del_role_group_modal">
                                    <Icon type="trash-a"></Icon> 删除当前角色组
                                </Button>
                            </ButtonGroup>
                        </div>
                        <Form ref="create_or_update_role_info_form"
                              :model="current_select_node_data"
                              :rules="role_group_info.rules"
                              :label-width="80">
                            <FormItem label="名称"
                                      prop="name">
                                <Input placeholder="请输入"
                                       v-model="current_select_node_data.name"
                                       style="width:300px;" />
                            </FormItem>
                            <FormItem label="编码"
                                      prop="code">
                                <Input placeholder="请输入"
                                       v-model="current_select_node_data.code"
                                       style="width:300px;" />
                            </FormItem>
                            <FormItem label="描述"
                                      prop="description">
                                <Input placeholder="请输入"
                                       v-model="current_select_node_data.description"
                                       style="width:300px;" />
                            </FormItem>
                            <FormItem label=" ">
                                <Button type="primary"
                                        @click="put_role_group_data">更新</Button>
                            </FormItem>
                        </Form>
                    </Card>
                    </Col>
                </Row>

                <!--新增角色组-->
                <Modal v-model="modals.create_or_update_role_group.is_show_modal"
                       :title="modals.create_or_update_role_group.title"
                       @on-ok="post_role_group">
                    <Form ref="create_role_group"
                          :model="modals.create_or_update_role_group.data"
                          :rules="role_group_info.rules"
                          :label-width="80">
                        <FormItem label="名称"
                                  prop="name">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_role_group.data.name"
                                   style="width:300px;" />
                        </FormItem>
                        <FormItem label="编码"
                                  prop="code">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_role_group.data.code"
                                   style="width:300px;" />
                        </FormItem>
                        <FormItem label="描述"
                                  prop="description">
                            <Input placeholder="请输入"
                                   v-model="modals.create_or_update_role_group.data.description"
                                   style="width:300px;" />
                        </FormItem>
                    </Form>
                </Modal>

                <!--菜单权限分配-->
                <Modal v-model="modals.access_allot.is_show_modal"
                       :title="modals.access_allot.title"
                       @on-ok="post_menu_authority">
                    <Row :gutter="16">
                        <Tree :data="modals.access_allot.menu_tree_data"
                              show-checkbox
                              multiple
                              @on-check-change="changeVal"></Tree>
                    </Row>
                </Modal>

                <!--页面元素权限分配-->
                <Modal v-model="modals.element_permission.is_show_modal"
                       ref="selection"
                       :title="modals.element_permission.title"
                       class-name="no-footer-modal"
                       width="900">
                    <Row :gutter="16">
                        <Col span="8">
                        <Card>
                            <Tree :data="modals.element_permission.menu_tree_data"
                                  @on-select-change="get_element_info"></Tree>
                        </Card>
                        </Col>
                        <Col span="16">
                        <Alert show-icon>勾选/取消勾选以后, 数据会立即保存</Alert>
                        <Table :columns="modals.element_permission.element_columns"
                               :data="modals.element_permission.elements_list_data"
                               @on-select="put_element_auth"
                               @on-select-cancel="del_element_auth"></Table>
                        </Col>
                    </Row>
                    <div slot="footer"></div>
                </Modal>

                <!--关联用户-->
                <Modal v-model="modals.connect_user.is_show_modal"
                       :loading="modals.connect_user.loading_post_connect_user"
                       :title="modals.connect_user.title"
                       @on-ok="put_connected_user">
                    <Form ref="connect_user_form"
                          :model="modals.connect_user.data"
                          :rules="modals.connect_user.rules"
                          :label-width="80">
                        <FormItem label="领导"
                                  prop="leaders">
                            <Select filterable
                                    multiple
                                    v-model="modals.connect_user.data.leaders">
                                <Option v-for="item in modals.connect_user.data.all_user"
                                        :value="item.value"
                                        :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                        <FormItem label="下属"
                                  prop="members">
                            <Select filterable
                                    multiple
                                    v-model="modals.connect_user.data.members">
                                <Option v-for="item in modals.connect_user.data.all_user"
                                        :value="item.value"
                                        :key="item.value">{{ item.label }}</Option>
                            </Select>
                        </FormItem>
                    </Form>
                </Modal>
            </div>
        </div>
    </div>
</template>
<script>
import {
	getTreeByRoleGroupType,
	postRoleGroup,
	getRoleGroupDetail,
	putRoleGroup,
	delRoleGroup,
	getTree,
	getMenuAccessByGroupId,
	getConnectUser,
	getUserByName,
	putConnectUser,
	postMenuAuthority,
	getElementList,
	getElementAuthorityList,
	postElementAuthority,
	delElementAuthority
} from '../../api/base_sys/base_manager'

export default {
	name: 'roleGroupOption',
	data() {
		return {
			role_group_tree_data: [],
			current_select_node_data: {}, // 当前选中的角色节点信息
			role_group_info: {
				data: {},
				rules: {}
			},
			modals: {
				create_or_update_role_group: {
					is_show_modal: false,
					title: '创建',
					data: {
						name: '',
						code: '',
						description: '',
						parentId: -1,
						groupType: this.type
					}
				},
				access_allot: {
					is_show_modal: false,
					title: '分配菜单权限',
					menu_tree_data: []
				},
				element_permission: {
					is_show_modal: false,
					title: '分配页面按钮权限',
					element_columns: [
						{
							type: 'selection',
							width: 60,
							align: 'center'
						},
						{
							title: 'id',
							key: 'id',
							width: 80
						},
						{
							title: '资源编码',
							key: 'code',
							width: 200
						},
						{
							title: '资源类型',
							key: 'type',
							width: 100
						},
						{
							title: '资源名称',
							key: 'name',
							width: 120
						},
						{
							title: '资源地址',
							key: 'uri',
							width: 220
						},
						{
							title: '资源请求类型',
							key: 'method',
							width: 120
						}
					],
					menu_tree_data: [],
					elements_list_data: [],
					selected_menu_item: null
				},
				connect_user: {
					is_show_modal: false,
					loading_post_connect_user: true,
					rules: {
						leaders: [
							{
								required: true,
								type: 'array',
								message: '新选择上级',
								trigger: 'change'
							}
						],
						members: [
							{
								required: true,
								type: 'array',
								message: '新选择下级',
								trigger: 'change'
							}
						]
					},
					title: '关联用户',
					data: {
						all_user: [],
						leaders: [],
						members: []
					}
				}
			},
			listQuery: {
				groupType: this.type,
				name: undefined
			}
		}
	},
	props: {
		type: {
			default: '1'
		}
	},
	methods: {
		changeVal(data) {
			console.log(data, 'data11111')
			// 将选中的数据只保留id传给后端  map()方法创建新数组
			var checkDataId = data.filter(i => i.id).map(j => j.id)
            // 方法二
			// var checkDataId = data.map(item => {
			// 	return item.id
			// })
			console.log(checkDataId, 'checkDataId')
		},
		//处理tree数据回显,obj：选中的数据(编辑时后端返回的)，arr：原数据
		formartData(obj, arr) {
			console.log(obj, '111', arr, '222')
			for (const key in obj) {
				console.log('66666666')
				let arr1 = []
				arr.map(item => {
					item.children.map(v => {
						obj.map(j => {
							console.log(v.id, 'v.id', j.id, 'j.id')
							if (v.id == j.id) {
								console.log('333333')

								v.checked = true // 选中数据的唯一标识与原数据的唯一标识相同，则给原数据加上checked，选中状态
								// arr1.push(v.title) // 这里是展示input框中显示的名字
							}
						})
					})
				})
			}
			let list = JSON.parse(JSON.stringify(arr))
			console.log(list, 'list')
			return list
		},
		// 角色树
		render_tree() {
			const _this = this
			getTreeByRoleGroupType(this.listQuery)
				.then(rs => {
					console.log(
						rs.data,
						'rs.data22222222222222222222222222222222======'
					)
					//   方法一：格式化树,父级及子级添加title字段
					const co = _this.format_role_map(rs.data)
					//   方法二：将后端返回的树形结构数据字段name变为Tree组件需要的字段title
					// rs.data = JSON.parse(JSON.stringify(rs.data).replace(/"name"/g,'"title"'))
					// console.log(rs.data)
					//    console.log(co,'co======')
					_this.role_group_tree_data = co
				})
				.catch(e => {
					console.log('e', e)
				})
		},
		// 格式化树,父级及子级添加title字段
		format_role_map(node) {
			const arr = []
			for (var i = 0; i < node.length; i++) {
				arr[i] = node[i]
				arr[i].title = node[i].name
				if (node[i].children.length > 0) {
					this.format_role_map(node[i].children)
				}
			}
			return arr
		},
		// 显示添加顶级角色组ffffffffffffff
		show_create_role_group_modal() {
			this.modals.create_or_update_role_group.is_show_modal = true
			this.modals.create_or_update_role_group.data = {}
			this.modals.create_or_update_role_group.data.groupType = this.type
			this.modals.create_or_update_role_group.data.parentId = -1
		},
		// 显示添加子角色组
		show_create_sub_role_group_modal() {
			this.modals.create_or_update_role_group.is_show_modal = true
			this.modals.create_or_update_role_group.data = {}
			this.modals.create_or_update_role_group.data.groupType = this.type
			this.modals.create_or_update_role_group.data.parentId = this.current_select_node_data.id
		},
		// 提交角色组
		post_role_group() {
			postRoleGroup(this.modals.create_or_update_role_group.data).then(
				rs => {
					this.render_tree()
				}
			)
		},
		// 获取角色组信息
		get_role_group_detail() {
			getRoleGroupDetail(id)
		},
		// 获取节点信息
		get_node_info(selected_data) {
			console.log(selected_data, '11111111111111111111111112222222')
			if (selected_data.length == 0) {
				return
			}

			getRoleGroupDetail(selected_data[0].id)
				.then(rs => {
					this.current_select_node_data = rs.data
					console.log(
						this.current_select_node_data,
						'this.current_select_node_data'
					)
				})
				.catch(e => {
					console.log('get_node_info error:', e)
				})
		},
		// 获取页面元素信息
		get_element_info(selected_data) {
			const _this = this
			_this.modals.element_permission.selected_menu_item =
				selected_data[0]
			getElementList({
				menuId: selected_data[0].id
			})
				.then(rs => {
					const element_list = rs.data
					getElementAuthorityList(_this.current_select_node_data.id)
						.then(element_authority_list_data => {
							const element_authority_list =
								element_authority_list_data.data
							for (var i = 0; i < element_list.length; i++) {
								if (
									element_authority_list.indexOf(
										element_list[i].id
									) > -1
								) {
									element_list[i]['_checked'] = true
								} else {
									element_list[i]['_checked'] = false
								}
							}
							_this.modals.element_permission.elements_list_data = element_list
						})
						.catch()
				})
				.catch(() => {})
		},
		// 更新角色组的信息
		put_role_group_data() {
			putRoleGroup(this.current_select_node_data)
				.then(rs => {
					this.$Message.success(rs.message)
				})
				.catch(() => {})
		},
		// 删除当前角色组
		show_del_role_group_modal() {
			const current_node = this.current_select_node_data
			const node_name = current_node.name
			this.$Modal.confirm({
				title: '删除确认',
				content: `确实删除名称为 <strong> ${node_name} </strong> 的角色组吗？`,
				onOk: () => {
					delRoleGroup(this.current_select_node_data)
						.then(rs => {
							if (rs.code === 0) {
								this.$Message.success('删除成功！')
								this.render_tree()
								this.current_select_node_data = {}
							} else {
								this.$Message.error(rs.message)
							}
						})
						.catch(() => {})
				},
				onCancel: () => {
					// this.$Message.info('Clicked cancel');
				}
			})
		},
		// 获取菜单树
		render_menu_tree() {
			const _this = this
			getTree()
				.then(rs => {
					let _tmp_tree_data = JSON.parse(JSON.stringify(rs.data))
					console.log(_tmp_tree_data, '555555555555555555555555')
					getMenuAccessByGroupId(this.current_select_node_data.id)
						.then(rss => {
							console.log(rss, 'rss134111111111')
							let access_id_list = []
							let final_list_data = []
							let subIds = [] // 获取所有最底层的id
							for (var j = 0; j < rss.data.length; j++) {
								access_id_list.push(rss.data[j].id)
								console.log(access_id_list, 'access_id_list')
							}

							_this.modals.access_allot.menu_tree_data = _this.filter_menu_selected(
								_tmp_tree_data,
								access_id_list,
								final_list_data
							)
							console.log(
								_this.modals.access_allot.menu_tree_data,
								'6666666666666666666666666666666'
							)
							// _this.modals.access_allot.menu_tree_data = _this.formartData(rss.data,_tmp_tree_data)
						})
						.catch(error => {
							console.log('error', error)
						})
				})
				.catch(() => {})
		},
		// 处理数据设置是否选中项,递归
		filter_menu_selected(origin_data_list, allow_array, access_list) {
			console.log(allow_array, '1111111112222222222222222222222222222')
			const arr = []
			for (var i = 0; i < origin_data_list.length; i++) {
				arr[i] = origin_data_list[i]
				arr[i].title = origin_data_list[i].label
				arr[i].hello = origin_data_list[i].label
				// arr[i].allow_array = allow_array.indexOf(origin_data_list[i]["id"]) > -1 && origin_data_list[i].children.length == 0 ? true : false;
				arr[i].checked =
					allow_array.indexOf(origin_data_list[i]['id']) > -1 &&
					origin_data_list[i].children.length == 0
						? true
						: false
				if (origin_data_list[i].children.length > 0) {
					this.filter_menu_selected(
						origin_data_list[i].children,
						allow_array,
						access_list
					)
				}
			}
			console.log(arr, 'arr33333333333333333333333333333')
			return arr
		},
		// // 处理数据设置是否选中项
		// filter_menu_selected(origin_data_list, access_list) {
		//     const arr = [];
		//     for (var i = 0; i < origin_data_list.length; i++) {
		//         arr[i] = origin_data_list[i];
		//         arr[i].title = origin_data_list[i].label;

		//         if (access_list.indexOf(arr[i]["id"]) > -1) {
		//             arr[i].checked = true;
		//         } else {
		//             arr[i].checked = false;
		//         }

		//         if (origin_data_list[i].children.length > 0) {
		//             console.log('zilei',origin_data_list[i])
		//             this.filter_menu_selected(origin_data_list[i].children, access_list);
		//         }
		//     }
		//     // console.log('arr',arr)
		//     return arr;
		// },
		// 获取页面权限菜单树
		render_menu_tree_without_checked() {
			const _this = this
			getTree()
				.then(rs => {
					const _tmp_tree_data = JSON.parse(JSON.stringify(rs.data))
					_this.modals.element_permission.menu_tree_data = _tmp_tree_data
				})
				.catch(() => {})
		},
		// 获取选中的菜单项
		get_all_selected_menu_id_list(tree_data_list, arr) {
			// const arr = [];
			for (var i = 0; i < tree_data_list.length; i++) {
				if (
					tree_data_list[i]['checked'] === true &&
					tree_data_list[i].children.length == 0
				) {
					arr.push(tree_data_list[i].id)
					console.log(arr, 'arr1111')
				}
				if (tree_data_list[i].children.length > 0) {
					this.get_all_selected_menu_id_list(
						tree_data_list[i].children,
						arr
					)
					console.log(arr, 'arr2222')
				}
			}
			return arr
		},
		// 显示菜单权限分配modal
		show_access_allot_modal() {
			this.modals.access_allot.is_show_modal = true
			this.render_menu_tree()
		},
		// 显示页面元素权限分配modal
		show_element_permission_modal() {
			this.modals.element_permission.is_show_modal = true
			this.modals.element_permission.elements_list_data = []
			this.render_menu_tree_without_checked()
		},
		// 显示关联用户modal
		show_connect_user_modal() {
			const _this = this
			this.modals.connect_user.is_show_modal = true
			getUserByName({
				name: ''
			})
				.then(rs => {
					_this.modals.connect_user.data.all_user = _this.filter_member_leader(
						rs.data.data
					)
					// 获取选中项
					getConnectUser(this.current_select_node_data.id)
						.then(rs => {
							const members_leaders_obj = _this.connected_users_id(
								rs.data
							)
							_this.modals.connect_user.data.members =
								members_leaders_obj.members
							_this.modals.connect_user.data.leaders =
								members_leaders_obj.leaders
						})
						.catch(err => {
							console.log('err', err)
						})
				})
				.catch(err => {
					console.log('err', err)
				})
		},
		// 处理数据，符合select规范
		filter_member_leader(data_list) {
			const arr = []
			for (var i = 0; i < data_list.length; i++) {
				var element = data_list[i]
				arr.push({
					value: element['id'],
					label: element['name']
				})
			}
			return arr
		},
		// 处理数据返回关联用户id列表
		connected_users_id(arr) {
			const obj = {},
				members = [],
				leaders = []
			arr.members.forEach(function(element) {
				members.push(element.id)
			}, this)
			arr.leaders.forEach(function(element) {
				leaders.push(element.id)
			}, this)
			obj.members = members
			obj.leaders = leaders
			return obj
		},
		change_put_connected_user_loading() {
			this.modals.connect_user.loading_post_connect_user = false
			this.$nextTick(() => {
				this.modals.connect_user.loading_post_connect_user = true
			})
		},
		// 保存关联用户数据
		put_connected_user() {
			const _this = this,
				_id = this.current_select_node_data.id,
				_query = {
					leaders: this.modals.connect_user.data.leaders.join(','),
					members: this.modals.connect_user.data.members.join(',')
				}
			this.$refs['connect_user_form'].validate(valid => {
				if (!valid) {
					return this.change_put_connected_user_loading()
				}
				putConnectUser(_id, _query)
					.then(rs => {
						_this.change_put_connected_user_loading()
						_this.modals.connect_user.loading_post_connect_user = true
						_this.modals.connect_user.is_show_modal = false
						_this.$Message.success(rs.message)
					})
					.catch(error => {
						_this.$Message.error(error)
					})
			})
		},
		// 保存菜单权限
		post_menu_authority() {
			const _this = this
			const selected_menu_list = this.get_all_selected_menu_id_list(
				this.modals.access_allot.menu_tree_data,
				[]
			).join(',')
			console.log(selected_menu_list, 'selected_menu_list')
			postMenuAuthority(this.current_select_node_data.id, {
				menuTrees: selected_menu_list
			})
				.then(rs => {
					_this.$Message.success('权限分配成功')
				})
				.catch(error => {
					_this.$Message.error(error)
				})
		},
		// 保存页面元素权限
		post_element_authority() {
			// 选中项数据
			// modals.element_permission.elements_list_data
		},
		// 过滤页面选中项数据
		put_element_auth(selection, row) {
			let _this = this,
				_element_id = row.id,
				_menu_id =
					_this.modals.element_permission.selected_menu_item.id,
				_group_id = _this.current_select_node_data.id
			postElementAuthority(_group_id, {
				menuId: _menu_id,
				elementId: _element_id
			})
				.then(rs => {
					console.log('rs', rs)
				})
				.catch(error => {
					console.log('error', error)
				})
		},
		// 删除页面元素权限
		del_element_auth(selection, row) {
			let _this = this,
				_element_id = row.id,
				_menu_id =
					_this.modals.element_permission.selected_menu_item.id,
				_group_id = _this.current_select_node_data.id
			delElementAuthority(_group_id, {
				menuId: _menu_id,
				elementId: _element_id
			})
				.then(rs => {
					console.log('rs', rs)
				})
				.catch(error => {
					console.log('error', error)
				})
		}
	},
	created() {
		this.render_tree()
	}
}
</script>
<style lang="less">
.no-footer-modal {
	.ivu-modal-footer {
		padding: 0;
		border-top: none;
	}
}
</style>